package com.sq.swing.frame;

import java.awt.*;
import javax.swing.*;
import java.awt.print.*;

public class PrintUtilities implements Printable {
	private Component componentToBePrinted;

	public static void printComponent(Component c) {
		new PrintUtilities(c).print();
	}

	public PrintUtilities(Component componentToBePrinted) {
		this.componentToBePrinted = componentToBePrinted;
	}

	public void print() {
		PrinterJob printJob = PrinterJob.getPrinterJob();

		printJob.setPrintable(this,printJob.defaultPage());
		if (printJob.printDialog())
			try {
				printJob.print();
			} catch (PrinterException pe) {
				System.out.println("Error printing: " + pe);
			}
	}

	public int print(Graphics g, PageFormat pageFormat, int pageIndex) {

		Graphics2D g2d = (Graphics2D) g;
		try {
			g2d.setColor (Color.black);

			Dimension d = componentToBePrinted.getSize();
			double panelWidth = d.width;
			double panelHeight = d.height;
			double pageWidth = pageFormat.getImageableWidth();
			double pageHeight = pageFormat.getImageableHeight();
			double scale = pageWidth / panelWidth;
			int totalNumPages = (int)Math.ceil(scale * panelHeight / pageHeight);

			if (pageIndex >= totalNumPages) {
				return (NO_SUCH_PAGE);
			} else {
				g2d.translate(pageFormat.getImageableX(), pageFormat
						.getImageableY());
				g2d.translate(0f, -pageIndex * pageHeight);
				g2d.scale(scale, scale);

				disableDoubleBuffering(componentToBePrinted);
				componentToBePrinted.paint(g2d);
				enableDoubleBuffering(componentToBePrinted);
				return (PAGE_EXISTS);
			}
		} finally {
			g2d.dispose();
		}
	}

	public static void disableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(false);
	}

	public static void enableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(true);
	}
}